package com.mxt.moviedemo.controller;

import com.mxt.moviedemo.entity.User;
import com.mxt.moviedemo.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("admin")
public class AdminController {
    private static final Logger logger = LoggerFactory.getLogger(AdminController.class);

    @Autowired
    private UserService userService;

    @PostMapping("login")
    public Map<String, Object> login(@RequestParam("adminUsername") String uname,
                                     @RequestParam("adminPassword") String password) {
        logger.info("Received username: {}, password: {}", uname, password);
        Map<String, Object> result = new HashMap<>();
        try {
            User admin = userService.loginByUsernameAndPassword(uname, password, "管理员");
            logger.info("Login result: {}", admin);
            if (admin != null) {
                result.put("success", true);
                result.put("message", "登录成功");
                result.put("redirectUrl", "/adminSuccessPage");
                result.put("username", admin.getUname());
            } else {
                result.put("success", false);
                result.put("message", "用户名或密码错误");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "登录失败：" + e.getMessage());
        }
        return result;
    }
}